#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import json
import time
import random
import shutil
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QTextEdit, QLineEdit,
    QFileDialog, QMessageBox, QGroupBox, QFormLayout, QSpinBox, QComboBox, 
    QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView, QProgressBar,
    QApplication, QCheckBox, QInputDialog, QDialog, QDialogButtonBox
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QColor
import configparser


class AccountManager(QWidget):
    """账号管理界面"""
    
    def __init__(self, config_file='accounts.json'):
        super().__init__()
        self.config_file = config_file
        self.accounts = self._load_accounts()
        self.init_ui()
        
    def _load_accounts(self):
        """加载账号信息"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return {}
        return {}
        
    def _save_accounts(self):
        """保存账号信息"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.accounts, f, ensure_ascii=False, indent=2)
        
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 添加账号按钮
        self.add_account_btn = QPushButton("添加账号")
        self.add_account_btn.clicked.connect(self.show_add_account_dialog)
        layout.addWidget(self.add_account_btn)
        
        # 账号列表
        self.accounts_table = QTableWidget(0, 10)
        self.accounts_table.setHorizontalHeaderLabels([
            "账号名称", "目标文件夹", "视频类目", "佣金率范围", "每日搬运数量", 
            "已搬运数量", "搬运状态", "修改", "操作", "删除"
        ])
        header = self.accounts_table.horizontalHeader()
        if header:
            # 设置列宽策略
            header.setSectionResizeMode(0, QHeaderView.Fixed)  # 账号名称列固定宽度
            header.setSectionResizeMode(1, QHeaderView.ResizeToContents)  # 目标文件夹列根据内容调整
            header.setSectionResizeMode(2, QHeaderView.Fixed)  # 视频类目列固定宽度
            header.setSectionResizeMode(3, QHeaderView.Fixed)  # 佣金率范围列固定宽度
            header.setSectionResizeMode(4, QHeaderView.Fixed)  # 每日搬运数量列固定宽度
            header.setSectionResizeMode(5, QHeaderView.Fixed)  # 已搬运数量列固定宽度
            header.setSectionResizeMode(6, QHeaderView.Fixed)  # 搬运状态列固定宽度
            header.setSectionResizeMode(7, QHeaderView.Fixed)  # 修改列固定宽度
            header.setSectionResizeMode(8, QHeaderView.Fixed)  # 操作列固定宽度
            header.setSectionResizeMode(9, QHeaderView.Fixed)  # 删除列固定宽度
            
            # 设置具体列宽
            header.resizeSection(0, 120)  # 账号名称列
            header.resizeSection(1, 300)  # 目标文件夹列最小宽度300
            header.resizeSection(2, 80)   # 视频类目列（窄一半）
            header.resizeSection(3, 80)   # 佣金率范围列（窄一半）
            header.resizeSection(4, 80)   # 每日搬运数量列（窄一半）
            header.resizeSection(5, 80)   # 已搬运数量列（窄一半）
            header.resizeSection(6, 100)  # 搬运状态列（窄一半）
            header.resizeSection(7, 60)   # 修改列
            header.resizeSection(8, 80)   # 操作列
            header.resizeSection(9, 60)   # 删除列
        v_header = self.accounts_table.verticalHeader()
        if v_header:
            v_header.setVisible(False)
        layout.addWidget(self.accounts_table)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新列表")
        refresh_btn.clicked.connect(self._refresh_accounts)
        layout.addWidget(refresh_btn)
        
        self.setLayout(layout)
        self._refresh_accounts()
        
    def show_add_account_dialog(self):
        """显示添加账号对话框"""
        dialog = AddAccountDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            # 添加成功后刷新列表
            self._refresh_accounts()
            QMessageBox.information(self, "提示", "账号添加成功")
            
    def show_edit_account_dialog(self, account_name):
        """显示修改账号对话框"""
        if account_name in self.accounts:
            dialog = EditAccountDialog(self, self.accounts[account_name])
            if dialog.exec_() == QDialog.Accepted:
                # 修改成功后刷新列表
                self._refresh_accounts()
                QMessageBox.information(self, "提示", "账号修改成功")
            
    def _refresh_accounts(self):
        """刷新账号列表"""
        self.accounts_table.setRowCount(0)
        for name, account in self.accounts.items():
            row = self.accounts_table.rowCount()
            self.accounts_table.insertRow(row)
            
            # 填充数据
            self.accounts_table.setItem(row, 0, QTableWidgetItem(account.get("name", "")))
            self.accounts_table.setItem(row, 1, QTableWidgetItem(account.get("folder", "")))
            self.accounts_table.setItem(row, 2, QTableWidgetItem(account.get("category", "")))
            self.accounts_table.setItem(row, 3, QTableWidgetItem(account.get("commission", "")))
            self.accounts_table.setItem(row, 4, QTableWidgetItem(str(account.get("daily_count", 0))))
            self.accounts_table.setItem(row, 5, QTableWidgetItem(str(account.get("moved_count", 0))))
            self.accounts_table.setItem(row, 6, QTableWidgetItem(account.get("status", "等待视频")))
            
            # 修改按钮
            edit_btn = QPushButton("修改")
            edit_btn.clicked.connect(lambda checked, n=name: self.show_edit_account_dialog(n))
            self.accounts_table.setCellWidget(row, 7, edit_btn)
            
            # 操作按钮
            start_btn = QPushButton("开始搬运")
            start_btn.clicked.connect(lambda checked, n=name: self.start_moving(n))
            self.accounts_table.setCellWidget(row, 8, start_btn)
            
            # 删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.clicked.connect(lambda checked, n=name: self.delete_account(n))
            self.accounts_table.setCellWidget(row, 9, delete_btn)
            
    def start_moving(self, account_name):
        """开始搬运"""
        if account_name in self.accounts:
            self.accounts[account_name]["status"] = "正在搬运"
            self._save_accounts()
            self._refresh_accounts()
            
    def delete_account(self, account_name):
        """删除账号"""
        reply = QMessageBox.question(self, "确认", f"确定要删除账号 {account_name} 吗？",
                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            if account_name in self.accounts:
                del self.accounts[account_name]
                self._save_accounts()
                self._refresh_accounts()
                
    def save_accounts(self):
        """保存账号信息"""
        self._save_accounts()
        
    def refresh_accounts(self):
        """刷新账号列表"""
        self._refresh_accounts()
        
    def select_folder(self):
        # 此方法已移至AddAccountDialog中
        pass
            
            
class AddAccountDialog(QDialog):
    """添加账号对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_widget = parent
        self.config_file = parent.config_file if parent else 'accounts.json'
        self.accounts = parent.accounts if parent else {}
        self.init_ui()
        
    def init_ui(self):
        self.setWindowTitle("添加账号")
        self.setModal(True)
        self.resize(400, 300)
        
        layout = QVBoxLayout()
        
        # 账号添加表单
        form_group = QGroupBox("账号信息")
        form_layout = QFormLayout()
        
        self.name_edit = QLineEdit()
        self.folder_edit = QLineEdit()
        self.folder_btn = QPushButton("选择文件夹")
        self.folder_btn.clicked.connect(self.select_folder)
        folder_layout = QHBoxLayout()
        folder_layout.addWidget(self.folder_edit)
        folder_layout.addWidget(self.folder_btn)
        
        self.commission_combo = QComboBox()
        commission_ranges = ["15-19", "20-24", "25-29", "30-34", "35-39", 
                           "40-44", "45-49", "50-54", "55-59", "其他"]
        self.commission_combo.addItems(commission_ranges)
        
        self.daily_count_spin = QSpinBox()
        self.daily_count_spin.setRange(1, 1000)
        self.daily_count_spin.setValue(10)
        
        self.category_combo = QComboBox()
        categories = ["食品饮料", "家居百货", "女装女鞋", "美妆护肤",
                     "个护清洁", "医疗保健", "母婴玩具", "茶酒生鲜",
                     "男装男鞋", "运动户外", "数码家电", "珠宝配饰"]
        self.category_combo.addItems(categories)
        
        form_layout.addRow("账号名称:", self.name_edit)
        form_layout.addRow("目标文件夹:", folder_layout)
        form_layout.addRow("视频类目:", self.category_combo)
        form_layout.addRow("佣金率范围:", self.commission_combo)
        form_layout.addRow("每日搬运数量:", self.daily_count_spin)
        
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept_account)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
        self.setLayout(layout)
        
    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择目标文件夹")
        if folder:
            self.folder_edit.setText(folder)
            
    def accept_account(self):
        """确认添加账号"""
        name = self.name_edit.text().strip()
        folder = self.folder_edit.text().strip()
        commission = self.commission_combo.currentText()
        daily_count = self.daily_count_spin.value()
        category = self.category_combo.currentText()
        
        if not name or not folder:
            QMessageBox.warning(self, "警告", "账号名称和目标文件夹不能为空")
            return
            
        if name in self.accounts:
            QMessageBox.warning(self, "警告", "账号名称已存在")
            return
            
        self.accounts[name] = {
            "name": name,
            "folder": folder,
            "commission": commission,
            "daily_count": daily_count,
            "category": category,
            "moved_count": 0,
            "status": "等待视频"
        }
        
        # 保存账号信息
        if self.parent_widget:
            self.parent_widget.accounts[name] = {
                "name": name,
                "folder": folder,
                "commission": commission,
                "daily_count": daily_count,
                "category": category,
                "moved_count": 0,
                "status": "等待视频"
            }
            self.parent_widget._save_accounts()
            self.parent_widget._refresh_accounts()
        
        # 关闭对话框
        self.accept()
        
    def save_accounts_to_file(self):
        """保存账号信息"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.accounts, f, ensure_ascii=False, indent=2)
            
    def _load_accounts(self):
        """加载账号信息"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return {}
        return {}
        
    def _save_accounts(self):
        """保存账号信息"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.accounts, f, ensure_ascii=False, indent=2)
            
    def add_account(self, name, folder, commission, daily_count, category):
        """添加账号"""
        if not name or not folder:
            QMessageBox.warning(self, "警告", "账号名称和目标文件夹不能为空")
            return False
            
        if name in self.accounts:
            QMessageBox.warning(self, "警告", "账号名称已存在")
            return False
            
        self.accounts[name] = {
            "name": name,
            "folder": folder,
            "commission": commission,
            "daily_count": daily_count,
            "category": category,
            "moved_count": 0,
            "status": "等待视频"
        }
        
        self._save_accounts()
        self._refresh_accounts()
        return True
        
    def _refresh_accounts(self):
        """刷新账号列表"""
        self.accounts_table.setRowCount(0)
        for name, account in self.accounts.items():
            row = self.accounts_table.rowCount()
            self.accounts_table.insertRow(row)
            
            # 填充数据
            self.accounts_table.setItem(row, 0, QTableWidgetItem(account.get("name", "")))
            self.accounts_table.setItem(row, 1, QTableWidgetItem(account.get("folder", "")))
            self.accounts_table.setItem(row, 2, QTableWidgetItem(account.get("commission", "")))
            self.accounts_table.setItem(row, 3, QTableWidgetItem(str(account.get("daily_count", 0))))
            self.accounts_table.setItem(row, 4, QTableWidgetItem(str(account.get("moved_count", 0))))
            self.accounts_table.setItem(row, 5, QTableWidgetItem(account.get("status", "等待视频")))
            
            # 操作按钮
            start_btn = QPushButton("开始搬运")
            start_btn.clicked.connect(lambda checked, n=name: self.start_moving(n))
            self.accounts_table.setCellWidget(row, 6, start_btn)
            
            # 删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.clicked.connect(lambda checked, n=name: self.delete_account(n))
            self.accounts_table.setCellWidget(row, 7, delete_btn)
            
    def start_moving(self, account_name):
        """开始搬运"""
        if account_name in self.accounts:
            self.accounts[account_name]["status"] = "正在搬运"
            self._save_accounts()
            self._refresh_accounts()
            
    def delete_account(self, account_name):
        """删除账号"""
        reply = QMessageBox.question(self, "确认", f"确定要删除账号 {account_name} 吗？",
                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            if account_name in self.accounts:
                del self.accounts[account_name]
                self._save_accounts()
                self._refresh_accounts()


class EditAccountDialog(QDialog):
    """修改账号对话框"""
    
    def __init__(self, parent=None, account_data=None):
        super().__init__(parent)
        self.parent_widget = parent
        self.account_data = account_data or {}
        self.config_file = parent.config_file if parent else 'accounts.json'
        self.accounts = parent.accounts if parent else {}
        self.init_ui()
        
    def init_ui(self):
        self.setWindowTitle("修改账号")
        self.setModal(True)
        self.resize(400, 350)
        
        layout = QVBoxLayout()
        
        # 账号信息（只读）
        info_group = QGroupBox("账号信息")
        info_layout = QFormLayout()
        
        self.name_label = QLabel(self.account_data.get("name", ""))
        info_layout.addRow("账号名称:", self.name_label)
        
        self.folder_edit = QLineEdit(self.account_data.get("folder", ""))
        self.folder_btn = QPushButton("选择文件夹")
        self.folder_btn.clicked.connect(self.select_folder)
        folder_layout = QHBoxLayout()
        folder_layout.addWidget(self.folder_edit)
        folder_layout.addWidget(self.folder_btn)
        info_layout.addRow("目标文件夹:", folder_layout)
        
        info_group.setLayout(info_layout)
        layout.addWidget(info_group)
        
        # 可修改的表单
        form_group = QGroupBox("可修改信息")
        form_layout = QFormLayout()
        
        # 视频类目下拉框
        self.category_combo = QComboBox()
        categories = ["食品饮料", "家居百货", "女装女鞋", "美妆护肤",
                     "个护清洁", "医疗保健", "母婴玩具", "茶酒生鲜",
                     "男装男鞋", "运动户外", "数码家电", "珠宝配饰"]
        self.category_combo.addItems(categories)
        # 设置当前选中值
        current_category = self.account_data.get("category", "")
        if current_category in categories:
            self.category_combo.setCurrentText(current_category)
        else:
            self.category_combo.setCurrentIndex(0)  # 默认选择第一个
        
        # 佣金率范围下拉框
        self.commission_combo = QComboBox()
        commission_ranges = ["15-19", "20-24", "25-29", "30-34", "35-39", 
                           "40-44", "45-49", "50-54", "55-59", "其他"]
        self.commission_combo.addItems(commission_ranges)
        # 设置当前选中值
        current_commission = self.account_data.get("commission", "")
        if current_commission in commission_ranges:
            self.commission_combo.setCurrentText(current_commission)
        else:
            self.commission_combo.setCurrentIndex(0)  # 默认选择第一个
        
        self.daily_count_spin = QSpinBox()
        self.daily_count_spin.setRange(1, 1000)
        self.daily_count_spin.setValue(self.account_data.get("daily_count", 10))
        
        form_layout.addRow("视频类目:", self.category_combo)
        form_layout.addRow("佣金率范围:", self.commission_combo)
        form_layout.addRow("每日搬运数量:", self.daily_count_spin)
        
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept_account)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
        self.setLayout(layout)
        
    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择目标文件夹")
        if folder:
            self.folder_edit.setText(folder)
            
    def accept_account(self):
        """确认修改账号"""
        folder = self.folder_edit.text().strip()
        commission = self.commission_combo.currentText()
        daily_count = self.daily_count_spin.value()
        category = self.category_combo.currentText()
        name = self.account_data.get("name", "")
        
        if not name:
            QMessageBox.warning(self, "警告", "账号名称不能为空")
            return
            
        if not folder:
            QMessageBox.warning(self, "警告", "目标文件夹不能为空")
            return
            
        # 更新账号信息
        if self.parent_widget and name in self.parent_widget.accounts:
            self.parent_widget.accounts[name].update({
                "folder": folder,
                "commission": commission,
                "daily_count": daily_count,
                "category": category
            })
            self.parent_widget._save_accounts()
            self.parent_widget._refresh_accounts()
        
        # 关闭对话框
        self.accept()

class VideoMover(QWidget):
    """视频搬运任务界面"""
    
    def __init__(self, account_manager):
        super().__init__()
        self.account_manager = account_manager
        self.source_folder = ""
        self.config_file = 'video_mover_config.json'  # 保存源文件夹配置的文件
        self.load_config()  # 加载配置
        self.init_ui()
        
    def load_config(self):
        """加载配置"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.source_folder = config.get('source_folder', '')
            except:
                self.source_folder = ''
        
    def save_config(self):
        """保存配置"""
        config = {
            'source_folder': self.source_folder
        }
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 源文件夹选择
        source_group = QGroupBox("源文件夹配置")
        source_layout = QHBoxLayout()
        
        self.source_edit = QLineEdit()
        self.source_edit.setText(self.source_folder)  # 设置保存的源文件夹路径
        self.source_btn = QPushButton("选择源文件夹")
        self.source_btn.clicked.connect(self.select_source_folder)
        self.refresh_btn = QPushButton("刷新统计")
        self.refresh_btn.clicked.connect(self.refresh_stats)
        
        source_layout.addWidget(QLabel("源文件夹:"))
        source_layout.addWidget(self.source_edit)
        source_layout.addWidget(self.source_btn)
        source_layout.addWidget(self.refresh_btn)
        
        source_group.setLayout(source_layout)
        layout.addWidget(source_group)
        
        # 类目统计
        stats_group = QGroupBox("源文件夹类目统计")
        stats_layout = QVBoxLayout()
        
        self.stats_text = QTextEdit()
        self.stats_text.setReadOnly(True)
        stats_layout.addWidget(self.stats_text)
        
        stats_group.setLayout(stats_layout)
        layout.addWidget(stats_group)
        
        # 搬运控制
        control_group = QGroupBox("搬运控制")
        control_layout = QHBoxLayout()
        
        self.start_all_btn = QPushButton("开始所有搬运任务")
        self.start_all_btn.clicked.connect(self.start_all_moving)
        self.stop_all_btn = QPushButton("停止所有搬运任务")
        self.stop_all_btn.clicked.connect(self.stop_all_moving)
        
        # 自动刷新设置
        self.auto_refresh_combo = QComboBox()
        self.auto_refresh_combo.addItems(["不自动刷新", "10秒", "30秒", "1分钟", "5分钟"])
        self.auto_refresh_combo.setCurrentText("30秒")
        self.auto_refresh_combo.currentTextChanged.connect(self.set_auto_refresh)
        
        self.auto_refresh_timer = QTimer()
        self.auto_refresh_timer.timeout.connect(self.auto_refresh)
        
        control_layout.addWidget(self.start_all_btn)
        control_layout.addWidget(self.stop_all_btn)
        control_layout.addWidget(QLabel("自动刷新:"))
        control_layout.addWidget(self.auto_refresh_combo)
        
        control_group.setLayout(control_layout)
        layout.addWidget(control_group)
        
        # 进度和日志
        progress_group = QGroupBox("搬运进度")
        progress_layout = QVBoxLayout()
        
        self.progress_bar = QProgressBar()
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        
        progress_layout.addWidget(self.progress_bar)
        progress_layout.addWidget(self.log_text)
        
        progress_group.setLayout(progress_layout)
        layout.addWidget(progress_group)
        
        self.setLayout(layout)
        self.set_auto_refresh("30秒")  # 默认30秒自动刷新
        
    def select_source_folder(self):
        """选择源文件夹"""
        folder = QFileDialog.getExistingDirectory(self, "选择源文件夹")
        if folder:
            self.source_folder = folder
            self.source_edit.setText(folder)
            self.save_config()  # 保存源文件夹配置
            self.refresh_stats()
            
    def refresh_stats(self):
        """刷新类目统计"""
        if not self.source_folder or not os.path.exists(self.source_folder):
            return
            
        # 统计各类目视频数量
        category_stats = {}
        for root, dirs, files in os.walk(self.source_folder):
            # 获取当前目录相对于源文件夹的路径
            rel_path = os.path.relpath(root, self.source_folder)
            if rel_path == ".":
                continue
                
            # 获取第一级子目录作为类目
            category = rel_path.split(os.sep)[0]
            if category not in category_stats:
                category_stats[category] = 0
                
            # 统计视频文件数量
            video_count = len([f for f in files if f.lower().endswith('.mp4')])
            category_stats[category] += video_count
            
        # 更新文本显示，一行显示4个类目
        stats_text = ""
        total_videos = 0
        categories = sorted(category_stats.items())
        for i, (category, count) in enumerate(categories):
            stats_text += f"{category}: {count} 个视频    "
            total_videos += count
            # 每4个类目换一行
            if (i + 1) % 4 == 0:
                stats_text += "\n"
        # 如果最后一行不足4个类目，也需要换行
        if len(categories) % 4 != 0:
            stats_text += "\n"
        stats_text += f"\n总计: {total_videos} 个视频"
        self.stats_text.setPlainText(stats_text)
            
    def set_auto_refresh(self, text):
        """设置自动刷新"""
        self.auto_refresh_timer.stop()
        if text == "10秒":
            self.auto_refresh_timer.start(10000)
        elif text == "30秒":
            self.auto_refresh_timer.start(30000)
        elif text == "1分钟":
            self.auto_refresh_timer.start(60000)
        elif text == "5分钟":
            self.auto_refresh_timer.start(300000)
            
    def auto_refresh(self):
        """自动刷新"""
        self.refresh_stats()
        self.check_and_move_videos()  # 检查并搬运视频
        
    def start_all_moving(self):
        """开始所有搬运任务"""
        for name in self.account_manager.accounts:
            self.account_manager.accounts[name]["status"] = "正在搬运"
        self.account_manager.save_accounts()
        self.account_manager.refresh_accounts()
        self.log_message("开始所有搬运任务")
        # 立即开始搬运，不等待自动刷新
        self.check_and_move_videos()
        
    def stop_all_moving(self):
        """停止所有搬运任务"""
        for name in self.account_manager.accounts:
            self.account_manager.accounts[name]["status"] = "等待视频"
        self.account_manager.save_accounts()
        self.account_manager.refresh_accounts()
        self.log_message("停止所有搬运任务")
        
    def check_and_move_videos(self):
        """检查并搬运视频"""
        if not self.source_folder or not os.path.exists(self.source_folder):
            return
            
        for name, account in self.account_manager.accounts.items():
            if account.get("status") == "正在搬运":
                self.move_videos_for_account(name, account)
                
    def move_videos_for_account(self, name, account):
        """为特定账号搬运视频"""
        try:
            target_folder = account.get("folder", "")
            daily_count = account.get("daily_count", 10)
            moved_count = account.get("moved_count", 0)
            
            if not target_folder:
                return
                
            # 确保目标文件夹存在
            os.makedirs(target_folder, exist_ok=True)
            
            # 查找源文件夹中的所有视频文件
            source_videos = []
            for root, dirs, files in os.walk(self.source_folder):
                for file in files:
                    if file.lower().endswith('.mp4'):
                        source_videos.append(os.path.join(root, file))
            
            if not source_videos:
                self.log_message(f"等待源视频: {name}")
                return
                
            # 计算还需要搬运的数量
            remaining_count = daily_count - moved_count
            if remaining_count <= 0:
                account["status"] = "已完成"
                self.account_manager.save_accounts()
                self.account_manager.refresh_accounts()
                return
                
            # 随机选择视频进行搬运
            videos_to_move = random.sample(source_videos, min(remaining_count, len(source_videos)))
            
            for video_file in videos_to_move:
                if moved_count >= daily_count:
                    break
                    
                source_path = video_file
                filename = os.path.basename(video_file)
                target_path = os.path.join(target_folder, filename)
                
                # 处理重名文件
                if os.path.exists(target_path):
                    base_name, ext = os.path.splitext(filename)
                    counter = 1
                    new_filename = f"{base_name}_{counter}{ext}"
                    target_path = os.path.join(target_folder, new_filename)
                    while os.path.exists(target_path):
                        counter += 1
                        new_filename = f"{base_name}_{counter}{ext}"
                        target_path = os.path.join(target_folder, new_filename)
                
                # 移动文件
                shutil.move(source_path, target_path)
                moved_count += 1
                
                # 记录日志
                self.log_message(f"已成功从 {source_path} 移动到 {target_path}")
                
            # 更新账号信息
            account["moved_count"] = moved_count
            if moved_count >= daily_count:
                account["status"] = "已完成"
            self.account_manager.save_accounts()
            self.account_manager.refresh_accounts()
            
        except Exception as e:
            self.log_message(f"搬运出错: {name} - {str(e)}")
            
    def log_message(self, message):
        """记录日志"""
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.log_text.append(f"[{timestamp}] {message}")
        self.log_text.moveCursor(self.log_text.textCursor().End)


class VideoMoverTool(QWidget):
    """视频搬运工具主界面"""
    
    def __init__(self):
        super().__init__()
        self.account_manager = None
        self.video_mover = None
        self.init_ui()
        
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 创建标签页
        tab_widget = QTabWidget()
        
        # 账号管理页签
        self.account_manager = AccountManager()
        tab_widget.addTab(self.account_manager, "账号管理")
        
        # 视频搬运页签
        self.video_mover = VideoMover(self.account_manager)
        tab_widget.addTab(self.video_mover, "视频搬运")
        
        layout.addWidget(tab_widget)
        self.setLayout(layout)
        self.setWindowTitle('视频搬运工具')
        self.resize(1200, 700)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = VideoMoverTool()
    window.show()
    sys.exit(app.exec_())